<template>
  <el-container>
    <el-header style="border-bottom: 2px solid #dee2e7">
      <h2 style="color: #50b4ff">本次诊断</h2>
    </el-header>
    <el-main style="padding: 0 0 0 10px;height:100%;overflow:hidden">
      <div v-if="!flag" v-loading="loading" style="position:relative;height:100%">
        <el-button v-if="!loading" @click="doGenerate" style="position:absolute;left:45%;top:45%;height:50px;width:150px">生成诊断结果</el-button>
      </div>
      <div v-if="flag" style="height: 100%">
        <div style="max-height: 65%;overflow:auto">
          <h3>智能化诊断分析</h3>
          <div class="card-div" v-for="(item,index) in list" :key="index">
            <div style="display:flex;align-items:center;padding-bottom: 10px" :class="{'analysing':item.analysing}">
              <el-checkbox v-model="item.chosen" @change="change($event, item)"></el-checkbox>
              <div style="margin-left:15px;width:100%">
                <div><span>{{ item.diseaseCode + '-' + item.diseaseName + '(' + item.levelName + ')' }}</span><el-tag @click="showKnowledge(item.name)" style="padding:2px;margin-left:10px;height:17px;line-height:12px;cursor: pointer">知</el-tag></div>
                <el-progress :percentage="item.itemResult" ></el-progress>
                <span style="font-size:smaller;color:#626262">医生/医疗组+g病历名称</span>
              </div>
              <el-button :loading="item.analysing" size="mini" @click="analyse(item)">相似病历对比分析</el-button>
            </div>
            <div v-show="item.clicked" style="padding:10px">
              <div class="analysing-top">
                <span style="white-space: nowrap">选择相似病历概率</span>
                <div style="width:100%;">
                  <el-slider
                      v-model="item.range"
                      range
                      :max="100" @change="analyse(item)">
                  </el-slider>
                </div>
                <el-button :disabled="!item.similarChosen || item.similarChosen.length != 3" size="mini" :type="item.search ? 'info' : 'primary'" :loading="item.search" @click="contrast(item)">{{ item.search ? '病历对比中...' : '病历对比(' + (item.similarChosen ? item.similarChosen.length : 0) + '/3)'}}</el-button>
              </div>
              <div>
                <!-- <el-button size="mini" round v-for="(s, i) in item.similarity" :key="i" @click="chooseSimilar">{{ s }}</el-button> -->
                <el-checkbox-group 
                  v-model="item.similarChosen"
                  :min="0"
                  :max="3" style="display: flex">
                  <el-checkbox border v-for="(s, i) in item.similarity" :label="s" :key="i">{{ '病历' + (i + 1) }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <div v-if="res.length > 0" style="text-align:center;margin-top:20px;"><a href="javascript:void(0);" @click="more">更多</a></div>
        </div>
        <div style="height:35%;overflow-y:auto">
          <div class="head-div">
            <h3>诊断结果</h3>
            <el-button size="mini" @click="applyGenerate()">采用系统诊断</el-button>
            <el-button size="mini" @click="diseaseDialog = true">新增疾病</el-button>
          </div>
          <div style="display:flex;flex-wrap:wrap">
            <div class="item-div" v-for="(e, i) in tempOpen.diagnosis" :key="i">
              <el-checkbox v-model="e.chosen"></el-checkbox>
              <a href="javascript:void(0);" @click="result = true">{{ e.diseaseName }}</a>
              <i class="el-icon-close" @click="remove(i)"></i>
              <el-radio-group v-model="e.resultState" size="mini">
                <el-radio-button label="unconfirm">疑似</el-radio-button>
                <el-radio-button label="confirm">确诊</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>
      <el-dialog title="疾病相关知库" :visible.sync="knowledgeDialog">
        <el-tabs v-model="activeName">
          <el-tab-pane label="疾病分析" name="first">
            {{ knowledge }}
          </el-tab-pane>
          <el-tab-pane label="图片" name="second">
            图片
          </el-tab-pane>
          <el-tab-pane label="视频" name="third">视频</el-tab-pane>
        </el-tabs>
      </el-dialog>
      <el-dialog title="病历对比" width="90%" :visible.sync="contrastDialog">
        <!-- <div class="table" >
          <div class="column">
            <div class="td thead">病历名称</div>
            <div class="td">主诉</div>
            <div class="td">现病史</div>
            <div class="td">既往史</div>
            <div class="td">体格检查</div>
            <div class="td">检查检验</div>
            <div class="td">诊断结果</div>
          </div>
          <div class="column">
            <div class="td thead">当前病历</div>
            <div class="td" v-html="parseChiefComplaint(tempOpen.chiefComplaint, dictIndex)"></div>
            <div class="td" v-html="parseHPI(tempOpen.HPI, dictIndex)"></div>
            <div class="td" v-html="parsePastHistory(tempOpen.pastHistory, dictIndex)"></div>
            <div class="td" v-html="parsePE(tempOpen.PE)"></div>
            <div class="td" v-html="parseCheckout(tempOpen)"></div>
            <div class="td" v-html="parseDiagnosis(tempOpen.diagnosis)"></div>
          </div>
          <div class="column" v-for="(e, i) in contrastRecords" :key="i">
            <div class="td thead">{{ e.name }}</div>
            <div class="td" v-html="parseChiefComplaint(e.chiefComplaint, dictIndex)"></div>
            <div class="td" v-html="parseHPI(e.HPI, dictIndex)"></div>
            <div class="td" v-html="parsePastHistory(e.pastHistory, dictIndex)"></div>
            <div class="td" v-html="parsePE(e.PE, dictIndex)"></div>
            <div class="td" v-html="parseCheckout(e)"></div>
            <div class="td" v-html="parseDiagnosis(e.diagnosis)"></div>
          </div>
        </div> -->
        <table class="define-table" v-if="contrastDialog">
          <thead>
            <tr>
              <th>病历名称</th>
              <th>当前病历</th>
              <th>{{ contrastRecords[0].name }}</th>
              <th>{{ contrastRecords[1].name }}</th>
              <th>{{ contrastRecords[2].name }}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>主诉</td>
              <td v-html="parseChiefComplaint(tempOpen.chiefComplaint, dictIndex)"></td>
              <td v-html="parseChiefComplaint(contrastRecords[0].chiefComplaint, dictIndex)"></td>
              <td v-html="parseChiefComplaint(contrastRecords[1].chiefComplaint, dictIndex)"></td>
              <td v-html="parseChiefComplaint(contrastRecords[2].chiefComplaint, dictIndex)"></td>
            </tr>
            <tr>
              <td>现病史</td>
              <td v-html="parseHPI(tempOpen.HPI, dictIndex)"></td>
              <td v-html="parseHPI(contrastRecords[0].HPI, dictIndex)"></td>
              <td v-html="parseHPI(contrastRecords[1].HPI, dictIndex)"></td>
              <td v-html="parseHPI(contrastRecords[2].HPI, dictIndex)"></td>
            </tr>
            <tr>
              <td>既往史</td>
              <td v-html="parsePastHistory(tempOpen.pastHistory, dictIndex)"></td>
              <td v-html="parsePastHistory(contrastRecords[0].pastHistory, dictIndex)"></td>
              <td v-html="parsePastHistory(contrastRecords[1].pastHistory, dictIndex)"></td>
              <td v-html="parsePastHistory(contrastRecords[2].pastHistory, dictIndex)"></td>
            </tr>
            <tr>
              <td>体格检查</td>
              <td v-html="parsePE(tempOpen.PE)"></td>
              <td v-html="parsePE(contrastRecords[0].PE)"></td>
              <td v-html="parsePE(contrastRecords[1].PE)"></td>
              <td v-html="parsePE(contrastRecords[2].PE)"></td>
            </tr>
            <tr>
              <td>检查检验</td>
              <td v-html="parseCheckout(tempOpen)"></td>
              <td v-html="parseCheckout(contrastRecords[0])"></td>
              <td v-html="parseCheckout(contrastRecords[1])"></td>
              <td v-html="parseCheckout(contrastRecords[2])"></td>
            </tr>
            <tr>
              <td>诊断结果</td>
              <td v-html="parseDiagnosis(tempOpen.diagnosis)"></td>
              <td v-html="parseDiagnosis(contrastRecords[0].diagnosis)"></td>
              <td v-html="parseDiagnosis(contrastRecords[1].diagnosis)"></td>
              <td v-html="parseDiagnosis(contrastRecords[2].diagnosis)"></td>
            </tr>
          </tbody>
        </table>
      </el-dialog>
      <el-dialog title="鉴别诊断" :visible.sync="identify">
        相关的鉴别诊断内容,如检查化验等信息
      </el-dialog>
      <el-dialog title="疾病库" width="30%" :visible.sync="diseaseDialog">
        <!-- <el-transfer
          filterable
          :filter-method="filterMethod"
          :titles="['待选', '已选']"
          filter-placeholder="请输入疾病"
          v-model="diseaseCodes"
          :props="{
            key: 'diseaseCode',
            label: 'diseaseName'
          }"
          :data="diseases">
        </el-transfer> -->
        <el-select
          v-model="manuallyCode"
          @change="diseaseChange"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="diseaseLoading">
          <el-option
            v-for="item in diseases"
            :key="item.diseaseCode"
            :label="item.diseaseName"
            :value="item.diseaseCode">
          </el-option>
        </el-select>
        <!-- <el-checkbox-group v-model="checkList">
          <el-checkbox label=""></el-checkbox>
        </el-checkbox-group> -->
      </el-dialog>
      <!-- <el-dialog title="诊断结果编辑" width="30%" :visible.sync="result">
        <el-input placeholder="搜索" prefix-icon="el-icon-search" ></el-input>
        <el-checkbox-group>
          <el-checkbox v-for="d in diseases" :label="d.name" :key="d.name"></el-checkbox>
        </el-checkbox-group>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog> -->
    </el-main>
  </el-container>
</template>

<script>
import { mapGetters } from 'vuex'
import { generate, similarity } from '@/api/diagnosis'
import { saveRecord, getRecordsByIds } from '@/api/record'
import { parseChiefComplaint, parseHPI, parsePastHistory, parsePE, parseCheckout, parseDiagnosis } from '@/utils/index'
import { getDisease } from '@/api/dict'

  export default {
    name: 'PreliminaryDiagnosis',
    data() {
      return {
        similarChosen: 0,
        flag: false,
        loading: false,
        diseaseLoading: false,
        knowledgeDialog: false,
        contrastDialog: false,
        diseaseDialog: false,
        result: false,
        activeName: 'first',
        identify: false,
        diseases: [],
        list: [],
        res: [],
        diseaseKnowledge: {
          '肺水肿': '肺水肿是指由于某种原因引起肺内组织液的生成和回流平衡失调，使大量组织液在很短时间内不能被肺淋巴和肺静脉系统吸收，从肺毛细血管内外渗，积聚在肺泡、肺间质和细小支气管内，从而造成肺通气与换气功能严重障碍。在临床上表现为极度的呼吸困难，端坐呼吸，发绀，大汗淋漓，阵发性咳嗽伴大量白色或粉红色泡沫痰，双肺布满对称性湿啰音。',
          '肺炎': '老年肺炎常缺乏明显呼吸系症状，症状多不典型，病情进展快，易发生漏诊、错诊。首发症状为呼吸急促及呼吸困难，或有意识障碍、嗜睡、脱水、食欲减退等。',
          '肺结核': '结核病是由结核分枝杆菌引起的慢性传染病，可侵及许多脏器，以肺部结核感染最为常见。排菌者为其重要的传染源。人体感染结核菌后不一定发病，当抵抗力降低或细胞介导的变态反应增高时，才可能引起临床发病。若能及时诊断，并予合理治疗，大多可获临床痊愈。',
          '肺癌': '肺癌是发病率和死亡率增长最快，对人群健康和生命威胁最大的恶性肿瘤之一。近50年来许多国家都报道肺癌的发病率和死亡率均明显增高，男性肺癌发病率和死亡率均占所有恶性肿瘤的第一位，女性发病率占第二位，死亡率占第二位。肺癌的病因至今尚不完全明确，大量资料表明，长期大量吸烟与肺癌的发生有非常密切的关系。已有的研究证明：长期大量吸烟者患肺癌的概率是不吸烟者的10～20倍，开始吸烟的年龄越小，患肺癌的几率越高。此外，吸烟不仅直接影响本人的身体健康，还对周围人群的健康产生不良影响，导致被动吸烟者肺癌患病率明显增加。城市居民肺癌的发病率比农村高，这可能与城市大气污染和烟尘中含有致癌物质有关。因此应该提倡不吸烟，并加强城市环境卫生工作。'
        },
        knowledge: '',
        contrastRecords: [1, 2, 3],
        manuallyCode: [],
        oldManuallyCode: []
      }
    },
    methods: {
      remoteMethod(query) {
        this.diseaseLoading = true
        getDisease(query).then(res => {
          this.diseaseLoading = false
          this.diseases = res.data
        })
      },
      diseaseChange(value) {
        // 增加自选疾病
        if (this.manuallyCode.length > this.oldManuallyCode.length) {
          this.manuallyCode.forEach(e => {
            if (!this.oldManuallyCode.includes(e)) {
              this.tempOpen.diagnosis.push({
                diseaseCode: e,
                diseaseName: e + '-' +this.diseaseIndex[e],
                resultState: 'unconfirm',
                _type: 'manually'
              })
            }
          })
        } else {
          this.oldManuallyCode.forEach(e => {
            if (!this.manuallyCode.includes(e)) {
              this.$set(this.tempOpen, 'diagnosis', this.tempOpen.diagnosis.filter(x => x.diseaseCode == e))
            }
          })
        }
        this.oldManuallyCode = this.manuallyCode
      },
      parseChiefComplaint,
      parseHPI,
      parsePastHistory,
      parsePE,
      parseCheckout,
      parseDiagnosis,
      filterMethod(query, item) {
        if (query && item) {
          return item.diseaseName.indexOf(query) > -1
        }
        return true
      },
      applyGenerate() {
        let count = this.list.length > 6 ? this.list.length : 6
        for(let i = 0; i < count; i ++) {
          this.tempOpen.diagnosis.push({
            diseaseCode: this.list[i].diseaseCode,
            diseaseName: this.list[i].diseaseCode + '-' + this.list[i].diseaseName,
            resultState: 'unconfirm'
          })
        }
      },
      remove(i) {
        this.diseaseCodes = this.diseaseCodes.filter(e => e != this.tempOpen.diagnosis[i].diseaseCode)
        this.tempOpen.diagnosis.splice(i, 1)
      },
      more() {
        this.list = this.list.concat(this.res.splice(0, 6))
      },
      doGenerate() {
        this.loading = true
        this.$store.dispatch('saveRecord', this.templateId).then(res => {
          console.log('保存病历成功!')
          generate(this.tempOpen.patientInfo.id, this.templateId).then(res => {
            this.flag = true
            this.loading = false
            res.data.forEach(e => {
              e.similarChosen = [],
              e.range = [70, 100],
              e.clicked = false
            })
            this.res = res.data
            this.list = this.res.splice(0, 6)
          }).catch(err => {
            console.log(err)
            this.loading = false
          })
        }).catch(err => {
          this.loading = false
        })
      },
      analyse(item) {
        this.$set(item, 'analysing', !item.analysing)
        this.$set(item, 'clicked', true)
        similarity(this.tempOpen._id, item.diseaseCode, item.range[0] / 100, item.range[1] / 100).then(res => {
          if (res.data.length > 0) {
            this.$set(item, 'similarity', res.data)
          } else {
            this.$set(item, 'similarity', [])
            this.$message('未找到相似病历!')
          }
          this.$set(item, 'analysing', !item.analysing)
        }).catch(err => {
          this.$set(item, 'analysing', !item.analysing)
        })
      },
      contrast(item) {
        getRecordsByIds(item.similarChosen).then(res => {
          this.contrastRecords = res.data
          this.contrastDialog = true
        })
      },
      showKnowledge(name) {
        this.knowledgeDialog = true
        this.knowledge = this.diseaseKnowledge[name]
      },
      change(flag, item) {
        if (flag) {
          this.diseaseCodes.push(item.diseaseCode)
          this.tempOpen.diagnosis.push({
            diseaseCode: item.diseaseCode,
            diseaseName: item.diseaseCode + '-' + item.diseaseName,
            resultState: 'unconfirm',
            _type: 'computer'
          })
        } else {
          this.tempOpen.diagnosis = this.tempOpen.diagnosis.filter(e => e.diseaseName != item.diseaseName)
        }
      }
    },
    computed: {
      ...mapGetters([
        'tempOpen',
        'dictIndex'
      ]),
      templateId() {
        return this.$route.query.templateId
      },
      diseaseIndex: function() {
        let obj = {}
        this.diseases.forEach(e => {
          obj[e.diseaseCode] = e.diseaseName
        })
        return obj
      }
    },
    mounted() {
      this.diseaseCodes = this.tempOpen.diagnosis.map(e => e.diseaseCode)
      this.remoteMethod('')
      this.list.map(e => {
        this.tempOpen.diagnosis.forEach(ele => {
          if (ele.diseases == e.name) {
            e.chosen = true
          }
        })
      })
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .table {
    font-size: 0;
    width: 99%;
  }
  .thead {
    background-color: #ccc;
    font-weight: bold;
  }
  .column {
    font-size: 10pt;
    display: inline-table;
    width: 20%;
  }
  .td{
    border: 1px solid;
    text-align: center;
    min-height: 80px;
    padding: 20px;
  }
  .el-icon-close {
    visibility: hidden;
    color: red;
    cursor: pointer;
    margin-left: 20px;
  }
  .item-div:hover {
    .el-icon-close {
      visibility: visible;
    }
  }
  .card-div {
    padding: 10px 20px 5px 0;
    border-radius: 5px;
  }
  .analysing {
    border-bottom: 1px solid #f4f4f4;
  }
  .card-div:hover {
    box-shadow:#f4f4f4 0px 0px 10px
  }
  .analysing-top {
    display: flex;
    align-items: center;
    * {
      margin-left: 10px;
      &:first-child {
        margin-left: 0;
      }
    }
  }
  .item-div {
    // flex: 1;
    width: 45%;
    margin: 10px 20px;
    border-bottom: 1px solid #d7dce2;
    position: relative;
    height: 40px;
    display: flex;
    align-items: center;
    span {
      margin-left: 20px;
    }
    .el-radio-group {
      position: absolute;
      right: 0;
    }
  }
  .head-div {
    display:flex;
    align-items:center;
    * {
      margin-right: 10px;
    }
  }
  .define-table{
    width: 100%;
    height: 100%;
    border-collapse:collapse;
    border-spacing:0;
    border-left:1px solid #888;
    border-top:1px solid #888;
    thead > tr {
      height: 40px;
    }
    tbody > tr {
      height: 80px;
    }
  }
  .define-table th,.define-table td{
    border-right:1px solid #888;
    border-bottom:1px solid #888;
    padding:5px 15px;
  }
  .define-table th{
    font-weight:bold;background:#ccc;
  }
  .el-checkbox {
    margin: 10px 10px;
    padding: 5px 5px;
    display: block;
  }
</style>
<style  rel="stylesheet/scss" lang="scss">
  .card-div {
    .el-button--primary {
      background-color: orange;
      border-color: orange;
    }
    .el-slider__bar {
      background-color: orange;
    }
    .el-slider__button {
      border: 2px solid orange;
    }
  }
</style>
